package spring.library.LibraryProject.server;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spring.library.LibraryProject.enums.BookStatusEnum;
import spring.library.LibraryProject.model.bookInfo;
import spring.library.LibraryProject.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.library.LibraryProject.model.pageResponse;

import java.util.List;

@Slf4j
@Service
public class booksServer {

    private Logger logger = LoggerFactory.getLogger(booksServer.class);

    @Autowired
    bookInfoMapper bookInfoMapper;
    @Autowired
    loginMapper loginMapper;
    //其实server可以直接使用mapper的dao和mapper存在一个就好

    //密码验证
    public Boolean verify(String username, String password) {
        return loginMapper.selectLoginInfoByNameAndPassword(username, password) != null;
    }

    public Boolean addBook(bookInfo bookInfo) {
        return bookInfoMapper.addBookInfo(bookInfo) != 0;
    }

    //删除书
    public boolean del(Integer id) {

        return bookInfoMapper.deleteBookInfoById(id, BookStatusEnum.DELETE.getCode()) != 0;
    }

    //调整书的内容
    public Boolean adjust(int id, String name, String author,
                          String count, String price, String publisher, String state) {
        return bookInfoMapper.updateBookInfo(toNull(id, name, author
                , count, price, publisher, state)) != 0;

    }

    //将空字符串变为null
    private bookInfo toNull(int id, String name, String author, String count, String price, String publisher, String state) {
        bookInfo b = new bookInfo();
        b.setId(id);
        b.setName(name.isEmpty() ? null : name);
        b.setAuthor(author.isEmpty() ? null : author);
        b.setCount(count.isEmpty() ? null : Integer.parseInt(count));
        b.setPrice(price.isEmpty() ? null : Integer.parseInt(price));
        b.setPublisher(publisher.isEmpty() ? null : publisher);
        b.setState(state.isEmpty() ? null : Integer.parseInt(state));
        b.setStateCN(b.getState() == 1 ? "可借阅" : "不可借阅");
        return b;
    }



    //批量删除
    public Boolean dels(String[] bookId) {
        int ret = 0;
        for (String bookId1 : bookId) {
            ret += bookInfoMapper.deleteBookInfoById(Integer.parseInt(bookId1),BookStatusEnum.DELETE.getCode());
        }
        return ret != 0;
    }

    //查询所有
    public List<bookInfo> getBookList() {
        return bookInfoMapper.getBookInfoAll();
    }

    //获得页信息
    public pageResponse getPageInfo(pageResponse page) {
        page.setTotalPages(bookInfoMapper.getBookCount());
        page.setBooks(bookInfoMapper.getBookInfoByPage(page));
        return page;
    }
}
